<template>
  <Swiper
    @swiper="onSwiper"
    :autoplay="{ delay: 600, pauseOnMouseEnter: true }"
    :modules="modules"
    :navigation="{
      nextEl: nextDomRef,
      prevEl: prevDomRef,
    }"
    class="relative my-swiper"
  >
    <SwiperSlide v-for="item in imgList" :key="item">
      <img :src="item" alt="" />
    </SwiperSlide>
    <button
      class="absolute left-0 top-1/2 z-10 -translate-y-1/2 bg-red-500 py-5 my-nav-btn"
      ref="prevDomRef"
      @click="onPrev"
      @mouseout="onStartPlay"
    >
      向前
    </button>
    <button
      class="absolute right-0 top-1/2 z-10 -translate-y-1/2 bg-red-500 py-5 my-nav-btn"
      ref="nextDomRef"
      @click="onNext"
      @mouseout="onStartPlay"
    >
      向后
    </button>
  </Swiper>
</template>

<script setup lang="ts">
import { Autoplay, Navigation, Pagination, Scrollbar } from 'swiper'
import type { Swiper } from 'swiper'
import 'swiper/css/autoplay'
import 'swiper/css/navigation'
import { ref } from 'vue'

const modules = [Autoplay, Navigation, Pagination, Scrollbar]
//@ts-ignore
const basePath = import.meta.env.BASE_URL
console.log('basePath', basePath)
const imgList = new Array(4).fill(true).map((_, index) => `${basePath}swiper-pic/0${index + 1}.jpg`)

const prevDomRef = ref<HTMLButtonElement>()
const nextDomRef = ref<HTMLButtonElement>()
const swiperInstance = ref<Swiper>()
function onSwiper(swiper: Swiper) {
  swiperInstance.value = swiper
}
function onPrev() {
  swiperInstance.value?.slidePrev()
}
function onNext() {
  swiperInstance.value?.slideNext()
}
function onStartPlay() {
  swiperInstance.value?.autoplay.start()
}
</script>

<style scoped lang="scss">
.my-swiper {
  .my-nav-btn {
    opacity: 0.3;
    transition: opacity 0.3s;
  }
  &:hover {
    .my-nav-btn {
      opacity: 1;
    }
  }
}
</style>
